import axios from 'axios'
import Vue from 'vue'

import Vuex from 'vuex'
Vue.use(Vuex)



const store = new Vuex.Store({
    // ...
    state: {
        list: [],

    },
    //同步获取数据给list 从异步actions传过来的
    mutations: {
        goodlist(state, newlist) {
            state.list = newlist
        },
        //点击全选控制反选的
        setckeck(state, val) {
            state.list.forEach(item => {
                item.goods_state = val
            })
        }
    },
    actions: {
        async setgoodlist(store) {
            const arr = await axios({
                url: 'https://www.escook.cn/api/cart'
            })
            store.commit('goodlist', arr.data.list)
        }
    },
    getters: {
        total(state) {
            return state.list.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)
        },
        totalprice(state) {
            return state.list.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },
        // 全选
        allCheck(state) {
            return state.list.every((obj) => obj.goods_state === true)
        },
        // 报错
        // allChec(state) {
        //     console.log(state.check);

        // }
    }


})

export default store
